package mybatis.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;


public class MyBatisUtils {

    private static ThreadLocal<SqlSession> sessionThreadLocal = new ThreadLocal<>();
    private static SqlSessionFactory sessionFactory;

    private static SqlSession getSession() throws Exception {
        if (sessionFactory == null) {
            InputStream inputStream = Resources.getResourceAsStream("mybatis.xml");
            sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        }
        SqlSession sqlSession = sessionFactory.openSession();
        sessionThreadLocal.set(sqlSession);
        return sqlSession;
    }


    public static <T> T getMapper(Class<T> mapperClass) {
        //需要一个sqlsession
        SqlSession sqlSession = sessionThreadLocal.get();
        //如果是空的,就获取一个sqlsession
        if (sqlSession == null) {
            try {
                sqlSession = getSession();//初始化会话
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        T mapper = sqlSession.getMapper(mapperClass);
        return mapper;

    }


    public static void commit() {
        //需要一个sqlsession
        SqlSession sqlSession = sessionThreadLocal.get();
        if (sqlSession != null) {//防止直接执行这个操作,没有执行前置的操作
            sqlSession.commit();
        }


    }

    public static void rollback() {
        //需要一个sqlsession
        SqlSession sqlSession = sessionThreadLocal.get();
        if (sqlSession != null) {
            sqlSession.rollback();
        }
    }

    public static void close() {
        SqlSession sqlSession = sessionThreadLocal.get();
        if (sqlSession != null) {
            sqlSession.close();
            sessionThreadLocal.remove();//清理移除
        }
    }
}
